package com.simon.hse.activity.danger;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonAdapter;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.CommonOutput;
import com.simon.hse.http.entity.DangerCommonDetailOutput;
import com.simon.hse.http.entity.DangerScheduleInput;
import com.simon.hse.http.entity.DropDownOutput;
import com.simon.hse.utils.DateTimeUtils;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;

/**
 * 隐患审批详情
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_danger_approval_detail)
public class DangerApprovalDetailActivity extends BaseActivity {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.ll_danger_approval_area)
    LinearLayout mLl_danger_approval_area;

    @ViewInject(R.id.tv_danger_approval_area)
    TextView mTv_danger_approval_area;

    @ViewInject(R.id.ll_danger_approval_position)
    LinearLayout mLl_danger_approval_position;

    @ViewInject(R.id.tv_danger_approval_position)
    TextView mTv_danger_approval_position;

    @ViewInject(R.id.ll_danger_approval_category)
    LinearLayout mLl_danger_approval_category;

    @ViewInject(R.id.tv_danger_approval_category)
    TextView mTv_danger_approval_category;

    @ViewInject(R.id.ll_danger_approval_check)
    LinearLayout mLl_danger_approval_check;

    @ViewInject(R.id.tv_danger_approval_check)
    TextView mTv_danger_approval_check;

    @ViewInject(R.id.ll_danger_approval_classify)
    LinearLayout mLl_danger_approval_classify;

    @ViewInject(R.id.tv_danger_approval_classify)
    TextView mTv_danger_approval_classify;

    @ViewInject(R.id.ll_danger_approval_level)
    LinearLayout mLl_danger_approval_level;

    @ViewInject(R.id.tv_danger_approval_level)
    TextView mTv_danger_approval_level;

    @ViewInject(R.id.ll_danger_approval_date)
    LinearLayout mLl_danger_approval_date;

    @ViewInject(R.id.tv_danger_approval_date)
    TextView mTv_danger_approval_date;

    @ViewInject(R.id.et_danger_approval_describe)
    TextView mEt_danger_approval_describe;

    @ViewInject(R.id.common_recyclerview)
    RecyclerView mRecyclerView;

    private CommonAdapter mCommonAdapter;
    private List<String> mDataBeanList = new ArrayList<>();
    private String id;
    private int schedule;//1已生效 2审批退回

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("隐患确认详情");

        initRecyclerView();
        initData();
    }

    @Event(value = {R.id.iv_common_left
            , R.id.ll_danger_approval_area, R.id.ll_danger_approval_position, R.id.ll_danger_approval_category, R.id.ll_danger_approval_classify
            , R.id.ll_danger_approval_check, R.id.ll_danger_approval_level, R.id.ll_danger_approval_date
            , R.id.tv_danger_approval_yes, R.id.tv_danger_approval_no})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.ll_danger_approval_area:
                // initCommonPop(mLl_danger_approval_area, mTv_danger_approval_area, MyApplication.getInstance().mDangerAreasList);
                break;
            case R.id.ll_danger_approval_position:
                // initCommonPop(mLl_danger_approval_position, mTv_danger_approval_position, MyApplication.getInstance().mDangerAreasList);
                break;
            case R.id.ll_danger_approval_category:
                // initCommonPop(mLl_danger_approval_category, mTv_danger_approval_category, MyApplication.getInstance().mDangerAreasList);
                break;
            case R.id.ll_danger_approval_check:
                // initCommonPop(mLl_danger_approval_check, mTv_danger_approval_check, MyApplication.getInstance().mDangerStandardsList);
                break;
            case R.id.ll_danger_approval_classify:
                // initCommonPop(mLl_danger_approval_classify, mTv_danger_approval_classify, MyApplication.getInstance().mDangerClassifyList);
                break;
            case R.id.ll_danger_approval_level:
                // initCommonPop(mLl_danger_approval_level, mTv_danger_approval_level, MyApplication.getInstance().mDangerLevelList);
                break;
            case R.id.ll_danger_approval_date:
                // findDate();
                break;
            case R.id.tv_danger_approval_yes:
                schedule = 1;
                agreeOrNot();
                break;
            case R.id.tv_danger_approval_no:
                schedule = 2;
                agreeOrNot();
                break;
        }
    }

    private void initRecyclerView() {
        GridLayoutManager glm = new GridLayoutManager(DangerApprovalDetailActivity.this, 4);
        // LinearLayoutManager llm = new LinearLayoutManager(DangerApprovalDetailActivity.this);
        mRecyclerView.setLayoutManager(glm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonAdapter = new CommonAdapter(DangerApprovalDetailActivity.this, R.layout.layout_item_danger_approval_pic, mDataBeanList);
        mCommonAdapter.setItemDataListener(new CommonAdapter.ItemDataListener<String>() {
            @Override
            public void setItemData(CommonViewHolder holder, String dataBean) {
                ImageView iv_danger_approval = holder.getView(R.id.iv_danger_approval);

                iv_danger_approval.setImageResource(R.mipmap.ic_launcher);

            }
        });

        mCommonAdapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {

            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonAdapter);
    }

    /**
     * 获取详情
     */
    private void initData() {
        Bundle extras = getIntent().getExtras();
        if (extras == null)
            return;
        id = extras.getString("ID");

        Call<String> call = HttpManager.getInstance().requestService().DANGER_COMMIN_DETAIL(id);
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                DangerCommonDetailOutput dangerCommonDetailOutput = new Gson().fromJson(result, DangerCommonDetailOutput.class);
                if (dangerCommonDetailOutput.getResult().equals("Success")) {
                    DangerCommonDetailOutput.DataBean dataBean = dangerCommonDetailOutput.getData();
                    for (DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean : MyApplication.getInstance().mDangerAreasList) {
                        if (valueBean.getKey().equals(dataBean.getRiskRegion())) {
                            mTv_danger_approval_area.setText(valueBean.getValue());
                        }
                    }
                    mTv_danger_approval_position.setText(dataBean.getRiskPosition());
                    mTv_danger_approval_category.setText(dataBean.getOrganizationType());
                    for (DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean : MyApplication.getInstance().mDangerStandardsList) {
                        Log.i("Simon", "dddddf = " + valueBean.getKey() + "  " + valueBean.getValue() + "  " + dataBean.getInspectType());
                        if (valueBean.getKey().equals(dataBean.getInspectType())) {
                            mTv_danger_approval_check.setText(valueBean.getValue());
                        }
                    }
                    for (DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean : MyApplication.getInstance().mDangerClassifyList) {
                        if (valueBean.getKey().equals(dataBean.getRiskType())) {
                            mTv_danger_approval_classify.setText(valueBean.getValue());
                        }
                    }
                    for (DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean : MyApplication.getInstance().mDangerLevelList) {
                        if (valueBean.getKey().equals(dataBean.getRiskLevel())) {
                            mTv_danger_approval_level.setText(valueBean.getValue());
                        }
                    }

                    String discoveryTime = dataBean.getDiscoveryTime();
                    mTv_danger_approval_date.setText(DateTimeUtils.convertCustomDate(discoveryTime));

                    mEt_danger_approval_describe.setText(dataBean.getRiskDescription());
                } else {
                    ToastUtils.getInstance().showShortToastBottom(dangerCommonDetailOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 同意 不同意
     */
    private void agreeOrNot() {
        DangerScheduleInput dangerScheduleInput = new DangerScheduleInput();
        dangerScheduleInput.setId(id);
        dangerScheduleInput.setSchedule(String.valueOf(schedule));

        Call<String> call = HttpManager.getInstance().requestService().DANGER_UPDATE_SCHEDULE(HttpManager.getInstance().requestBody(dangerScheduleInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                CommonOutput commonOutput  = new Gson().fromJson(result, CommonOutput.class);
                if (commonOutput.getResult().equals("Success")) {
                    finishActivity(DangerApprovalDetailActivity.this);
                } else {
                    ToastUtils.getInstance().showShortToastBottom(commonOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 排查情况Pop
     */
    private void initCommonPop(LinearLayout mLl, final TextView mTv, final List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mList) {
        View inflate = LayoutInflater.from(DangerApprovalDetailActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(DangerApprovalDetailActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(DangerApprovalDetailActivity.this, R.layout.layout_item_common_more_department, mList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DropDownOutput.DataBean.DataDicListBean.ValueBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DropDownOutput.DataBean.DataDicListBean.ValueBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getValue());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = mList.get(position);
                mTv.setText(valueBean.getValue());
                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(DangerApprovalDetailActivity.this, inflate, mLl);
    }

    /**
     * 隐患发现时间
     */
    private void findDate() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        startDate.set(1949, 1, 1);
        String currentYMD = "";
        String oldTime = mTv_danger_approval_date.getText().toString();
        if (TextUtils.isEmpty(oldTime)) {
            currentYMD = DateTimeUtils.getCurrentYMD();
        } else {
            currentYMD = oldTime.split(" ")[0];
        }
        String[] split0 = currentYMD.split("-");
        selectedDate.set(Integer.parseInt(split0[0]), Integer.parseInt(split0[1]) - 1, Integer.parseInt(split0[2]));
        String[] split1 = DateTimeUtils.getCurrentYMD().split("-");
        endDate.set(Integer.parseInt(split1[0]), Integer.parseInt(split1[1]) - 1, Integer.parseInt(split1[2]));

        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(DangerApprovalDetailActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                mTv_danger_approval_date.setText(sdf_ymd.format(date));
            }
        })
                .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .setLabel("年", "月", "日", "时", "分", "")//默认设置为年月日时分秒
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();

        pvTime.show();
    }
}
